package qimao.com.edu.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import qimao.com.edu.config.AppConfig;
import qimao.com.edu.entity.Works;
import qimao.com.edu.service.WorksService;
import qimao.com.edu.service.impl.WorksServiceImpl;

@WebServlet("/writer/submitNovel.do")
@MultipartConfig
public class SubmitNovelServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        PrintWriter out = response.getWriter();
        // 前端访问的相对路径
        String coverImgPath = null;
        // 文件保存路径
        Path savedFilePath = null;
        Works works = new Works();
        
        try {
            // 1. 获取表单数据
            String novelTitle = request.getParameter("novelTitle");
            String novelCategory = request.getParameter("novelCategory");
            System.out.println("获取的小说类型: " + novelCategory);
            String novelIntroduction = request.getParameter("novelIntroduction");
            String isOriginal = request.getParameter("isOriginal");
            int authorId = Integer.parseInt(request.getParameter("authorId"));
            
            // 2. 验证必填字段
            if (novelTitle == null || novelTitle.trim().isEmpty() ||
                novelCategory == null || novelCategory.trim().isEmpty() ||
                novelIntroduction == null || novelIntroduction.trim().isEmpty() ||
                isOriginal == null || isOriginal.trim().isEmpty()) {
                System.out.println("表单验证失败：存在必填字段为空");
                out.println("<script>");
                out.println("alert('请填写所有必填字段');");
                out.println("history.back();");
                out.println("</script>");
                return;
            }
            
            System.out.println("文件上传配置检查:");
            System.out.println("AppConfig.UPLOAD_PATH: " + AppConfig.UPLOAD_PATH);
            System.out.println("AppConfig.UPLOAD_URL: " + AppConfig.UPLOAD_URL);
            
            // 3. 处理封面图片上传
            Part filePart = request.getPart("coverImage");
            if (filePart != null && filePart.getSize() > 0) {
                System.out.println("开始处理文件上传...");
                System.out.println("提交的文件名: " + filePart.getSubmittedFileName());
                System.out.println("文件大小: " + filePart.getSize() + " 字节");
                
                // 生成唯一文件名
                String fileName = UUID.randomUUID().toString() + "_" + 
                    filePart.getSubmittedFileName();
                
                // 使用Path类构建完整路径
                Path uploadDir = Paths.get(AppConfig.UPLOAD_PATH, "imgs","bookImgs");
                System.out.println("上传目录: " + uploadDir);
                
                // 确保目录存在
                if (!Files.exists(uploadDir)) {
                    System.out.println("创建上传目录: " + uploadDir);
                    Files.createDirectories(uploadDir);
                } else {
                    System.out.println("上传目录已存在");
                }
                
                // 构建完整文件路径
                savedFilePath = uploadDir.resolve(fileName);
                System.out.println("保存文件路径: " + savedFilePath);
                
                // 保存文件（使用Files工具类）
                try (InputStream input = filePart.getInputStream()) {
                    System.out.println("开始写入文件...");
                    Files.copy(input, savedFilePath);
                    System.out.println("文件写入成功: " + savedFilePath);
                } catch (IOException e) {
                    System.err.println("文件写入失败: " + savedFilePath);
                    System.err.println("错误信息: " + e.getMessage());
                    e.printStackTrace();
                    throw e; // 重新抛出异常，进入统一错误处理
                }
                
                // 构建前端访问路径
                coverImgPath = "imgs/bookImgs/" + fileName;
                System.out.println("前端访问路径: " + coverImgPath);
            } else {
                System.out.println("没有上传封面图片");
            }
            
            // 4. 封装作品对象
            works.setTitle(novelTitle);
            works.setCategory(Integer.parseInt(novelCategory));
            works.setDescription(novelIntroduction != null ? novelIntroduction : "");
            works.setIsOriginal(isOriginal.equals("yes") ? 1 : 0);
            works.setCover(coverImgPath);
            works.setAuthor(authorId);
            
            // 打印到控制台
            System.out.println("提交的小说信息：");
            System.out.println("书名：" + novelTitle);
            System.out.println("作者ID：" + authorId);
            System.out.println("类别ID：" + novelCategory);
            System.out.println("封面路径：" + coverImgPath);
            
            // 5. 调用服务层创建作品
            WorksService ws = new WorksServiceImpl();
            int result = ws.createWork(works);
            
            if (result == 1) {
                System.out.println("作品创建成功，ID: " + result);
                // 返回成功响应
                out.println("<script>");
                out.println("alert('作品提交成功！');");
                out.println("window.location.href = 'index.html';");
                out.println("</script>");
            } else {
                System.out.println("作品创建失败，返回值: " + result);
                // 提交失败，删除已上传的封面图片
                deleteUploadedFile(savedFilePath);
                out.println("<script>alert('作品提交失败，请重试'); history.back();</script>");
            }

        } catch (Exception e) {
            System.err.println("处理请求时发生异常: " + e.getMessage());
            e.printStackTrace();
            
            // 发生异常时删除已上传的文件
            deleteUploadedFile(savedFilePath);
            
            out.println("<script>alert('发生错误，请稍后再试'); history.back();</script>");
        }
    }
    
    // 辅助方法：删除上传的文件
    private void deleteUploadedFile(Path filePath) {
        if (filePath != null && Files.exists(filePath)) {
            try {
                System.out.println("准备删除文件: " + filePath);
                Files.delete(filePath);
                System.out.println("文件已成功删除: " + filePath);
            } catch (IOException ex) {
                System.err.println("删除文件失败: " + filePath);
                System.err.println("错误信息: " + ex.getMessage());
                ex.printStackTrace();
            }
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doPost(request, response);
    }
}